import torch
import torch.nn as nn
import torch.nn.functional as F

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from tqdm import tqdm
import torch.nn.functional as F
import matplotlib.pyplot as plt

# 数据预处理
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])

# 加载 CIFAR-10 数据集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=2)

class FCNN(nn.Module):
    def __init__(self, num_classes=10, dropout=True):
        super(FCNN, self).__init__()
        self.dropout = dropout

        # 卷积层
        self.conv1 = nn.Conv2d(3, 20, kernel_size=3, stride=1, padding=1)
        self.conv2 = nn.Conv2d(20, 40, kernel_size=3, stride=1, padding=1)
        self.conv3 = nn.Conv2d(40, 40, kernel_size=3, stride=1, padding=1)
        self.conv4 = nn.Conv2d(40, 40, kernel_size=3, stride=1, padding=1)
        self.conv5 = nn.Conv2d(40, 40, kernel_size=3, stride=2, padding=1)

        # 初始化全连接层，稍后在 forward 中动态设置
        self.fc1 = None
        self.fc2 = nn.Linear(128, num_classes)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, kernel_size=2, stride=2)

        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, kernel_size=2, stride=2)

        x = F.relu(self.conv3(x))
        x = F.max_pool2d(x, kernel_size=2, stride=2)

        x = F.relu(self.conv4(x))
        x = F.max_pool2d(x, kernel_size=2, stride=2)

        x = F.relu(self.conv5(x))

        # 展平之前动态计算输入到全连接层的大小
        batch_size = x.size(0)
        x = x.view(batch_size, -1)  # 展平

        # 初始化全连接层
        if self.fc1 is None:
            self.fc1 = nn.Linear(x.size(1), 128)  # 根据特征图大小动态创建
            if self.dropout:
                self.dropout_layer = nn.Dropout(0.2)

        if self.dropout:
            x = self.dropout_layer(x)

        x = F.relu(self.fc1(x))
        if self.dropout:
            x = self.dropout_layer(x)
        out = self.fc2(x)
        return out

# 训练设置
device = torch.device( "cpu")  # 检查GPU是否可用
model = FCNN().to(device)  # 移动模型到GPU
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
losses = []

# 训练过程
num_epochs = 20  # 可以根据需要调整
for epoch in range(num_epochs):
    model.train()
    running_loss = 0.0
    for inputs, labels in tqdm(trainloader):
        inputs, labels = inputs.to(device), labels.to(device)  # 移动输入和标签到GPU

        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()

    print(f"Epoch [{epoch + 1}/{num_epochs}], Loss: {running_loss / len(trainloader):.4f}")
    losses.append(running_loss / len(trainloader))

# 绘制损失图
plt.plot(losses)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Training Loss Over Epochs')
plt.show()

# 测试过程
model.eval()
correct = 0
total = 0
with torch.no_grad():
    for inputs, labels in testloader:
        inputs, labels = inputs.to(device), labels.to(device)  # 移动输入和标签到GPU
        outputs = model(inputs)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print(f'Accuracy of the model on the 10000 test images: {100 * correct / total:.2f}%')
